import { DataTypes } from 'sequelize'
import {
  Table,
  Column,
  Model,
  Comment,
  AllowNull,
  BelongsTo,
  ForeignKey,
  Default,
  HasMany,
  PrimaryKey,
  AutoIncrement
} from 'sequelize-typescript'
import { InferAttributes, InferCreationAttributes } from 'sequelize/types'
import Comments from './Comments'
import User from './User'

@Table({
  //表名不自动添加s
  freezeTableName: true
})
class Blog extends Model<InferAttributes<Blog>, InferCreationAttributes<Blog>> {
  @PrimaryKey
  @AutoIncrement
  @Column
  blog_id?: number

  @Comment('用户id')
  @AllowNull(false)
  @ForeignKey(() => User)
  @Column
  user_id!: number

  @Comment('内容')
  @AllowNull(false)
  @Column({ type: DataTypes.TEXT })
  content!: string

  @Comment('图片')
  @Column({ type: DataTypes.STRING })
  //ts类型混乱，其实应该传入是string[]=>string，返回是string=>string[],但是setter和getter访问器ts类型混乱，所以any代替
  set image(value: any) {
    this.setDataValue('image', JSON.stringify(value))
  }
  get image(): any {
    return JSON.parse(this.getDataValue('image'))
  }

  @Comment('点赞数')
  @Default(0)
  @Column
  thumb_up?: number
  //需要查出此博客用户的信息用belongsto
  @BelongsTo(() => User)
  user?: User
  //需要查出此博客所有的评论用hasmany
  @HasMany(() => Comments)
  comments?: Comments[]
}
export default Blog
